package top.infopub.mgr.cap.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.PayfeeApplyDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.*;
import top.infopub.mgr.cap.domain.PayfeeApplyDomain;
import top.infopub.mgr.cap.jsonvo.PayfeeApplyJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.PayfeeApplyService;
import top.infopub.mgr.cap.vo.PayfeeApplyVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class PayfeeApplyServiceImpl extends GenericServiceImpl<PayfeeApply, String> implements PayfeeApplyService {

    @Autowired
    private PayfeeApplyDao payfeeApplyDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private PayfeeApplyAttDao payfeeApplyAttDao;

    @Autowired
    private PayfeeApplyDetailDao payfeeApplyDetailDao;
    @Autowired
    private top.infopub.mgr.cap.dao.FinancingPlanDao financingPlanDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private ContractGuarantyDao contractGuarantyDao;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Override
    public GenericDao<PayfeeApply, String> getDao() {
        return payfeeApplyDao;
    }

    @Override
    public Page<PayfeeApplyDomain> selectByDomainWhere(Page<PayfeeApplyDomain> page,
                                                       PayfeeApplyVo payfeeApplyVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<PayfeeApplyDomain>)payfeeApplyDao.selectByDomainWhere(payfeeApplyVo);
    }

    @Override
    public PayfeeApplyJsonVo queryDetailById(String id) {
        PayfeeApplyJsonVo jsonVo = new PayfeeApplyJsonVo();
        /*收款单位名称（下拉框）*/
        List<GuaranteeName> compNames= payfeeApplyDao.queryReceiverNames();
        jsonVo.setCompNames(compNames);
        //id不存在就新增
        if(StringUtils.isEmpty(id)){
            //项目名称下拉框
            List<FinancingName> financingNames = financingPlanDao.queryListFinancingName();
            jsonVo.setFinancingNames(financingNames);
//            /*付款单位名称（下拉框）*/
//            List<GuaranteeName> payNames=  payfeeApplyDao.queryPayNames();
//            jsonVo.setPayCompNames(payNames);
//            /*收款银行账号（下拉框）*/
//            List<ReceiverBankAccount> receiverAccounts=payfeeApplyDetailDao.queryListReceiverAccounts();
//            jsonVo.setReceiverAccounts(receiverAccounts);
//            /*付款银行账号 （下拉框）*/
//            List<PayBankAccount> payBankAccounts=payfeeApplyDetailDao.queryListPayAccounts();
//            jsonVo.setPayAccounts(payBankAccounts);
        }else{
            //否则查看详情
            /*融资基础信息*/
            PayfeeApplyDto dto=payfeeApplyDao.queryDetailById(id);
            jsonVo.setPayfeeApplyDto(dto);
            /*融资付费子表信息*/
            List<PayfeeApplyInfo> details= payfeeApplyDetailDao.queryDetailById(dto.getId());
            jsonVo.setInfos(details);
//            /*付款单位名称（下拉框）*/
//            List<GuaranteeName> payNames=  payfeeApplyDao.queryPayNames();
//            jsonVo.setPayCompNames(payNames);
//            /*收款银行账号（下拉框）*/
//            List<ReceiverBankAccount> receiverAccounts=payfeeApplyDetailDao.queryListReceiverAccounts();
//            jsonVo.setReceiverAccounts(receiverAccounts);
//            /*付款银行账号 （下拉框）*/
//            List<PayBankAccount> payBankAccounts=payfeeApplyDetailDao.queryListPayAccounts();
//            jsonVo.setPayAccounts(payBankAccounts);
            /*附件信息表*/
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(dto.getProCode(), ProjectFileTypeEnum.FILE_TYPE57.getCode(), null);
            jsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        }

        return jsonVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo edit(PayfeeApplyDto payfeeApplyDto, List<PayfeeApplyInfo> payfeeApplyInfo, List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
//        BeanUtils.copyProperties(payfeeApplyDto,payfeeApply);
        PayfeeApply tmpPi=new PayfeeApply();
        PayfeeApply payfeeApply=null;
        //判断id存不存在，存在就修改
        if(StringUtils.isNotEmpty(payfeeApplyDto.getId())){
            //校验数据是否存在
            tmpPi = payfeeApplyDao.selectByPrimaryKey(payfeeApplyDto.getId());
            if (tmpPi == null) return RspVo.getFailureResponse(400, "融资付费申请数据不存在");
            //判断审批状态
            if (org.apache.commons.lang.StringUtils.isNotBlank(tmpPi.getProcessStatus())
                    && (org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
                    || org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            payfeeApply=new PayfeeApply();
            payfeeApply.setId(payfeeApplyDto.getId());
            payfeeApply.setProCode(payfeeApplyDto.getProCode());
            payfeeApply.setUptBy(vo.getId());
            payfeeApply.setUptTime(new Date());
            payfeeApplyDao.updateByIdSelective(payfeeApply);

        }else{
            //新增主表
            payfeeApply=new PayfeeApply();
            payfeeApply.setCodes(IdFactory.getUUIDUpper());
            payfeeApply.setProCode(payfeeApplyDto.getProCode());
            payfeeApply.setAddBy(vo.getId());
            payfeeApply.setAddTime(new Date());
            payfeeApplyDao.insertSelective(payfeeApply);
        }

        //子表数据
        if(payfeeApplyInfo.size()>0 && payfeeApplyInfo !=null) {
            for(PayfeeApplyInfo infos : payfeeApplyInfo){
                infos.setUptBy(vo.getId());
                infos.setUptTime(new Date());
                if (StringUtils.isBlank(infos.getId())) {
                    infos.setAddBy(vo.getId());
                    infos.setAddTime(new Date());
                    infos.setPayfeeApplyId(payfeeApply.getId());
                    payfeeApplyDetailDao.insertSelective(infos);
                } else {
                    payfeeApplyDetailDao.updateByIdSelective(infos);
                }
            }
        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(payfeeApplyDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE57.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            if (StringUtils.isNotBlank(tmpPi.getOaId())) {
                oaFlowService.finishOA(tmpPi.getOaId());
            }
            PayfeeApplyJsonVo payAppJson = queryDetailById(payfeeApply.getId());
            List<GuaranteeName> compNames = payAppJson.getCompNames();
            List<PayfeeApplyInfo> infos = payAppJson.getInfos();
            if (compNames != null && compNames.size() > 0 && infos != null && infos.size() > 0) {
                List<GuaranteeName> tmpList = new ArrayList<>();
                for (PayfeeApplyInfo info : infos) {
                    if (info == null) continue;
                    for (GuaranteeName gn : compNames) {
                        if (gn == null) continue;
                        if (StringUtils.equals(gn.getId(), info.getReceiverName())
                                || StringUtils.equals(gn.getId(), info.getPayCompName())) {
                            tmpList.add(gn);
                            break;
                        }
                    }
                }
                payAppJson.setCompNames(tmpList);
            } else {
                payAppJson.setCompNames(null);
            }
            String detailJson= JSON.toJSONString(payAppJson);
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE19, detailJson, payfeeApply.getId(), payfeeApply.getProCode(), vo);

        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public RspVo modifyFinInfo(PayfeeApply payfeeApply, AuthorizationVO vo) {
        PayfeeApply pay=new PayfeeApply();
        BeanUtils.copyProperties(payfeeApply,pay);
        //校验数据是否存在
        PayfeeApply tmpPi = payfeeApplyDao.selectByPrimaryKey(payfeeApply.getId());
        if (tmpPi == null) return RspVo.getFailureResponse(400, "融资付费数据不存在");
        //判断审批状态
        if (!(StringUtils.isNotBlank(tmpPi.getProcessStatus())
                && StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }
        //修改财务信息，融资付费主表中
        pay.setUptBy(vo.getId());
        pay.setUptTime(new Date());
        payfeeApplyDao.updateByIdSelective(pay);
        return RspVo.getSuccessResponse();
    }


    @Override
    public Page<PayfeeApplyDomain> selectMyCheckByDomainWhere(Page<PayfeeApplyDomain> page,
                                                              PayfeeApplyVo payfeeApplyVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<PayfeeApplyDomain>)payfeeApplyDao.selectMyCheckByDomainWhere(payfeeApplyVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePayfeeApply(PayfeeApply payfeeApply,
                                List<PayfeeApplyDetail> payfeeApplyDetails,
                                List<PayfeeApplyAtt> payfeeApplyAtts) {
        //执行新增
        payfeeApplyDao.insertById(payfeeApply);

        //批量添加付费明细
        if (CollectionUtils.isNotEmpty(payfeeApplyDetails)) {
            payfeeApplyDetailDao.insertByBatch(payfeeApplyDetails);
        }

        //批量添加付费申请附件
        if (CollectionUtils.isNotEmpty(payfeeApplyAtts)) {
            payfeeApplyAttDao.insertByBatch(payfeeApplyAtts);
        }
        // 一亿 
        BigDecimal cmp = new BigDecimal("100000000");
        String srcBizTable = "CAP_PAYFEE_APPLY";
        String branchCode_lt = "pay_total<=1亿";
        String branchCode_gt = "pay_total>1亿";
        String templateId = "";
        // <=1亿
        if (payfeeApply.getPayTotal().compareTo(cmp) <= 0) {
            templateId = wsFlowProcess.queryTemplateIdByTableBranch(srcBizTable, branchCode_lt);
        }
        else {
            templateId = wsFlowProcess.queryTemplateIdByTableBranch(srcBizTable, branchCode_gt);
        }
        // 处理工作流数据
        wsFlowProcess.launch(templateId, srcBizTable, payfeeApply.getId(),
            payfeeApply.getProcessId(), null);
    }

    @Override
    public PayfeeApplyVo selectById(String id) {
        return payfeeApplyDao.selectById(id);
    }

    @Override
    public PayfeeApplyVo selectByGuid(String id) {
        return payfeeApplyDao.selectByGuid(id);
    }

    @Override
    public PayfeeApplyDto queryOneByProCode(String proCode) {
        return payfeeApplyDao.queryOneByProCode(proCode);
    }
}